from django.db.models import Q, OuterRef, Sum, Subquery
from rest_framework import generics

# 选择货品(商品)界面展示的列表内容
from purchase_info.serializer.purchase_serializer import ChoiceGoodsSerializer

from ERP_system.utils.pagination import GlobalPagination
from goods_info .models import *


class ChoiceGoodsView(generics.GenericAPIView):
    serializer_class = ChoiceGoodsSerializer
    pagination_class = GlobalPagination


    def post(self, request, *args, **kwargs):
        ser = ChoiceGoodsSerializer(data=request.data)
        if ser.is_valid():
            warehouse_id = ser.validated_data.get('warehouse_id', None)
            keyword = ser.validated_data.get('keyword', None)
            category_id = ser.validated_data.get('category_id', None)
            number_code = ser.validated_data.get('number_code', None)
            query = Q()
            if warehouse_id:  # 查询 每个商品的库存数量
                inventory_list = GoodsInventoryModel.objects.filter(id=warehouse_id).filter(goods_id=OuterRef('pk')).values(
                    'goods_id').annotate(total_sum=Sum('cur_inventory'))

            else:
                inventory_list = GoodsInventoryModel.objects.filter(goods_id=OuterRef('pk')).values(
                    'goods_id').annotate(total_sum=Sum('cur_inventory'))
            if keyword:
                child_query = Q()
                child_query.add(Q(name__contains=keyword), 'OR')
                child_query.add(Q(specification=keyword), 'OR')
                child_query.add(Q(model_number=keyword), 'OR')
                query.add(child_query, 'AND')
            if category_id:
                query.add(Q(category__id=category_id), 'AND')
            if number_code:
                query.add(Q(number_code__contains=number_code), 'AND')

            result = GoodsModel.objects.filter(query).values('id', 'name', 'number_code', 'specification',
                                                             'model_number', 'color', 'units__basic_name',
                                                             'category__name', 'category_id').annotate(cur_inventory=Subquery(inventory_list.values('total_sum'))).all()
            pg_result = self.paginate_queryset(result)

            result_ser = self.get_serializer(instance=pg_result, many=True)
        return self.get_paginated_response(result_ser.data)
